<?php

  date_default_timezone_set('Asia/Kolkata');
  session_start();

  $host = 'localhost';
  $username = 'root';
  $password = '';
  $dbname = 'mb127';

  # Will you like to print debug messages
  $isDebug = 0; // true / false
  $logArr = array();
  $msg = '';
  ########### MYSQL CONNECTION ##########
  mysql_connect($host,$username,$password) or die(mysql_error());

  mysql_select_db($dbname) or die(mysql_error());
  ########### MYSQL CONNECTION ##########

  ########  UPLAOD CONFIG ##############
  //$mb = 1.5;//MB
  //$allowedSize = $mb*1024*1024;//Bytes
  //$allowedExtn = array('doc','docx','jpeg','jpg');//try with pdf
  //$upload_dir = "./uploads";

  $rules = array('mb'=>1.5,
               'extn'=>array('doc','docx','jpeg','jpg','png'),
               'upload'=>'./uploads');


  #################################################


  function pr($arr = array(),$line='',$file='')
  {
    global $isDebug;
    global $logArr;
    if($isDebug == false) return false;
    $debug = '';
    if($line !='' || $file !='') {
      $debug = "$file on Line $line";
    }

    $debug .=  '<pre style="color:FFFFFF;background:#000000;padding:10px;border-radius:5px;width:100%">';
    $debug .= print_r($arr,1);
    $debug .= '</pre>';
    $logArr[] = $debug;
  }

  function pq($arr = array())
  {
    global $isDebug;
    global $logArr;

    if($isDebug == false) return false;
    $debug  = '<div style="color:FF0000;background:yellow;padding:10px;border-radius:5px;width:100%">';
    $debug .= print_r($arr,1);
    $debug  .= '</div>';
    $logArr[] = $debug;
  }


  function getStatus($status=0)
  {
    return $status == 0 ? '<span class="glyphicon glyphicon-star-empty"></span>':'<span class="glyphicon glyphicon-star"></span>';
  }


  function update($tableName='',$where='',$data=array())
  {
    if($tableName==''||$where=='') {
      return false;
    }
      $tmp = '';
      foreach($data as $colName=>$value) {
        $tmp .= "`$colName`='$value' ,";
      }
      $tmp = rtrim($tmp, ' ,');

    $query = "UPDATE `$tableName` SET $tmp WHERE $where";
    dbQuery($query);
    return mysql_affected_rows();
  }

  function countAll($tableName='',$where='')
  {
    if($tableName=='') {
      return false;
    }
    $where = $where!='' ? " WHERE $where" :'';

    $totalQuery = "SELECT COUNT(*) as `total` FROM `$tableName` $where";

    $totalResult = dbQuery($totalQuery);
    $totalAns = mysql_fetch_assoc($totalResult);
    return $totalAns['total'];
  }

  function fetchAll($tableName='',$where='',$fields='',$order='',$limit='')
  {
    if($tableName=='') {
      return false;
    }

    $where = $where!='' ? " WHERE $where" :'';
    $fields = $fields!='' ? $fields :'*';
    $order = $order!='' ? "ORDER BY $order" :'';
    $limit = $limit!='' ? "LIMIT $limit" :'';

    $totalQuery = "SELECT $fields FROM `$tableName` $where $order $limit";
    $totalResult = dbQuery($totalQuery);

    return $totalResult;
  }

  function delete($tableName='', $where='')
  {
    if($tableName==''||$where=='') {
      return false;
    }
    $where = $where!='' ? "WHERE $where" :'';
    $query = "DELETE FROM `$tableName`
              $where";
    dbQuery($query);
    return mysql_affected_rows();
  }


  function dbQuery($query='')
  {
    global $logArr;
    $result = mysql_query($query) or die(mysql_error());

    $traceArray = (array_reverse(debug_backtrace()));
    $file =$traceArray[0]['file'];
    $line = $traceArray[0]['line'];
    $logArr[] = "$file on Line $line";
    pq($query);
    return $result;
  }

  function arrayCleanup($array='')
  {
    $array = array_map('trim',$array);
    $array = array_map('mysql_real_escape_string',$array);
    $array = array_map('strip_tags',$array);
    return $array;
  }

  function dbInsert($tableName='',$fields=array())
  {
    if($tableName==''|| empty($fields)) {
      return false;
    }
      $query = "INSERT INTO `$tableName` SET ";
      $tmp = '';
      foreach($fields as $colName=>$value) {
        $tmp .= "`$colName`='$value' ,";
      }
      $tmp = rtrim($tmp, ' ,');
      $query = $query.$tmp;
      dbQuery($query);
      return mysql_insert_id();
  }

  function uploadFile($uploadName='',$rules=array())
  {
    if(empty($_FILES) || $uploadName=='') return false;

      $mb = $rules['mb'];//1.5;//MB
      $allowedSize = $mb*1024*1024;//Bytes
      $allowedExtn = $rules['extn']; //array('doc','docx','jpeg','jpg');//try with pdf
      $upload_dir = $rules['upload'];// "./uploads";
      $msg = $renamedName  ='';
      $flag = true;
    if(isset($_FILES[$uploadName]['error'])){
      if($_FILES[$uploadName]['error']==0){
        if($_FILES[$uploadName]['size'] > $allowedSize){
          $msg = "Please upload file with $mb MB max.";
          $flag = false;
        } else {
          $fileInfo = pathinfo($_FILES['avatar']['name']);
          if(in_array($fileInfo['extension'],$allowedExtn)) {

            if(is_uploaded_file($_FILES[$uploadName]['tmp_name'])){
              $src = $_FILES[$uploadName]['tmp_name'];
              $fileName = $_FILES[$uploadName]['name'];
              # Following file name should be set in db
              $upload_file_name = date('ymdHis').'_'.uniqid().'_'.$fileName;

              $dest = $upload_dir.'/'.$upload_file_name;

              if(move_uploaded_file($src,$dest)){
                $msg = "file ($fileName) uploaded successfully";

                $renamedName = $upload_file_name;


              } else {
                $msg = "Please check your upload directory permission.<br>Please try again.";
                $flag = false;
              }
            } else {
              $msg = "There might be some error during upload.Please try again.";
              $flag = false;
            }

          } else {
            $msg = "Please upload file with valid extn ".implode(',',$allowedExtn).'.';
            $flag = false;
          }

        }
      } else if($_FILES[$uploadName]['error']!=4){
        $msg = "Please upload file with $mb MB max.";
        $flag = false;
      }
    }
      return array('flag'=>$flag,
                  'msg'=>$msg,
                  'renamedName'=>$renamedName);
  }//uploadFile()
